//
//  SFOAuthViewController.swift
//  SFWeiboPro
//
//  Created by happy on 2017/9/13.
//  Copyright © 2017年 happy. All rights reserved.
//

import UIKit
import SVProgressHUD

class SFOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        view.backgroundColor = UIColor.white
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))
        
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(SFAppKey)&redirect_uri=\(SFRedirectURL)"
        
        guard let url = URL(string: urlStr) else {
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
    }
    
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = 'cylushengfu@163.com';" + "document.getElementById('passwd').value = 'lsf513068';"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }

    @objc func close() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
}


extension SFOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("新浪授权登录----\(String(describing: request.url?.absoluteString))")
        
        // "code="
        //是否跳回调页面
        if request.url?.absoluteString.hasPrefix(SFRedirectURL) == false {
            
            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            
            close()
            
            return false
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码 -- \(code)")
        
        SFNetworkManager.shareManager.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络数据错误")
            }else {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                //登录成功发送通知
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: SFUserLogonSuccessNotification),
                    object: nil)
                
                self.close()
//                let keyWindow = UIApplication.shared.keyWindow
//                
//                keyWindow?.rootViewController = SFTabBarViewController()
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
